<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 信用分展示 -->
      <el-col :span="8" :xs="24">
        <el-card class="score-card">
          <div slot="header" class="clearfix">
            <span class="card-title">我的信用分</span>
          </div>
          <div class="score-display">
            <div class="score-number">{{ userScore.totalScore || 600 }}</div>
            <div class="score-desc">信用等级：{{ getCreditLevel(userScore.totalScore || 600) }}</div>
            <div class="score-update-time" v-if="userScore.lastUpdateTime">
              最近更新：{{ parseTime(userScore.lastUpdateTime, '{y}-{m}-{d} {h}:{i}') }}
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 守约记录摘要 -->
      <el-col :span="16" :xs="24">
        <el-card class="dimension-card">
          <div slot="header" class="clearfix">
            <span class="card-title">守约记录</span>
            <router-link to="/creditlife/record" style="float: right; padding: 3px 0">查看全部</router-link>
          </div>
          <div class="compliance-content">
            <div class="stats-row">
              <div class="stat-card">
                <div class="stat-value">{{ totalCompliance }}</div>
                <div class="stat-label">总守约次数</div>
              </div>
              <div class="stat-card">
                <div class="stat-value">{{ recentComplianceRate }}%</div>
                <div class="stat-label">近期守约率</div>
              </div>
            </div>
            <div class="records-table">
              <div class="table-header">
                <div class="col-type">类型</div>
                <div class="col-desc">描述</div>
                <div class="col-date">日期</div>
              </div>
              <div
                v-for="(record, index) in recentRecords"
                :key="index"
                class="table-row"
              >
                <div class="col-type">[{{ record.type }}]</div>
                <div class="col-desc">{{ record.description }}</div>
                <div class="col-date">{{ record.date }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 提升任务 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="task-card">
          <div slot="header" class="clearfix">
            <span class="card-title">提升任务</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8" :xs="24" v-for="(task, index) in taskList" :key="task.taskId">
              <div class="task-item" :style="{ '--item-index': index }">
                <div class="task-title">
                  <span class="task-icon">{{ getTaskIcon(task.taskType) }}</span>
                  {{ task.taskName }}
                </div>
                <div class="task-desc">{{ task.taskDesc }}</div>
                <div class="task-reward">
                  <span class="reward-label">奖励积分超过</span>
                  <span class="reward-score">+{{ task.scoreReward }}</span>
                </div>
                <div class="task-type-tag">
                  <el-tag :type="getTaskTypeTagType(task.taskType)" size="small">
                    {{ getTaskTypeName(task.taskType) }}
                  </el-tag>
                </div>
                <div class="task-action">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleTaskAction(task)"
                    :disabled="task.completed"
                    :loading="task.loading"
                  >
                    {{ task.completed ? '已完成' : '去完成' }}
                  </el-button>
                </div>
              </div>
            </el-col>
          </el-row>
          <div v-if="taskList.length === 0" class="no-data">
            暂无可用任务
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getScoreNoAuth, analyDimenNoAuth, getTaskNoAuth, completeTask, getCreditHistoryNoAuth, getComplianceRecords, getComplianceStats } from "@/api/credit/score";
import * as echarts from 'echarts';
import { getCurrentUserRealInfo } from "@/api/user_profile/user_auth.js"; // 新增导入

export default {
  name: "CreditScore",
  data() {
    return {
      userScore: {},
      dimensionData: {},
      taskList: [],
      creditHistory: [],
      dimensionChart: null,
      hasRealNameAuth: false, // 新增状态
      // 守约记录相关数据
      complianceData: {
        total: 0,
        recentRate: 0,
        records: [],
        types: []
      }
    };
  },
  computed: {
    // 计算属性 - 使用真实数据替代原来的静态数据
    totalCompliance() {
      return this.complianceData.total;
    },
    recentComplianceRate() {
      return this.complianceData.recentRate;
    },
    recentRecords() {
      return this.complianceData.records;
    }
  },
  created() {
    this.getScoreInfo();
    this.getTaskList();
    // this.getCreditHistory();
    this.checkRealNameAuth(); // 新增检查实名状态
    this.loadComplianceData(); // 加载守约记录数据
  },
  mounted() {
    // 增加实名事件监听
    this.$bus.$on('real-name-auth-updated', (hasAuth) => {
      this.hasRealNameAuth = hasAuth;
      this.getTaskList(); // 重新获取任务列表
    });
  },
  beforeDestroy() {
    this.$bus.$off('real-name-auth-updated');
  },
  methods: {
    // Helper function to map recordType numbers to meaningful strings
    getRecordTypeName(recordType) {
      switch (recordType) {
        case 1:
          return '信用租赁'; // Example: Map 0 to '信用消费'
        case 2:
          return '酒店预定'; // Example: Map 1 to '公共服务'
        case 3:
          return '便捷泊车'; // Example: Map 2 to '交通出行'
        // Add more cases as per your backend's recordType definitions
        default:
          return '舒心就医';
      }
    },
    // 加载守约记录数据
    async loadComplianceData() {
      try {
        // 获取统计数据
        const statsResponse = await getComplianceStats();
        if (statsResponse.code === 200) {
          this.complianceData.total = statsResponse.data.totalRecords || 0;
          this.complianceData.recentRate = statsResponse.data.recentComplianceRate || 0;
          this.complianceData.types = statsResponse.data.typeDistribution || [];
        }

        // 获取最近记录
        const recordsResponse = await getComplianceRecords({
          pageNum: 1,
          pageSize: 5,
        });
        if (recordsResponse.code === 200 && recordsResponse.rows) {
          this.complianceData.records = recordsResponse.rows.map(record => ({
            type: this.getRecordTypeName(record.recordType),
            description: record.description || '守约行为',
            date: this.formatDate(record.completeTime || record.dueTime)
          }));
        } else {
          console.error('获取守约记录失败: 后端返回数据结构不正确或为空。', recordsResponse);
          this.complianceData.records = []; // 清空数据，避免前端显示错误
        }
      } catch (error) {
        console.error('获取守约记录失败:', error);
      }
    },
    // 日期格式化函数
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return `${date.getFullYear()}.${(date.getMonth() + 1).toString().padStart(2, '0')}.${date.getDate().toString().padStart(2, '0')}`;
    },
    // 新增方法：检查实名认证状态
    async checkRealNameAuth() {
      try {
        const res = await getCurrentUserRealInfo();
        this.hasRealNameAuth = res.data && !!res.data.name;
      } catch (error) {
        console.error("检查实名认证状态出错:", error);
        this.hasRealNameAuth = false;
      }
    },
    /** 获取信用分信息 */
    getScoreInfo() {
      getScoreNoAuth().then(response => {
        this.userScore = response.data;
      });
    },
    /** 获取任务列表 */
    getTaskList() {
      getTaskNoAuth().then(response => {
        let tasks = response.data.taskList || [];

        // 如果已经实名认证，过滤掉实名任务
        if (this.hasRealNameAuth) {
          tasks = tasks.filter(task => task.taskId !== 1); // 假设实名任务的ID是1
        }

        this.taskList = tasks;
      });

    },
    // /** 获取信用分历史记录 */
    // getCreditHistory() {
    //   getCreditHistoryNoAuth().then(response => {
    //     this.creditHistory = response.data.rows || [];
    //   });
    // },
    /** 处理任务行为 */
    handleTaskAction(task) {
      console.log(task.taskId)
      // 如果是实名认证任务，跳转到用户资料页
      if (task.taskId === 1) { // 实名的id是1
        // console.log("是1")
        this.$router.push('/credit/user_profile');
        return;
      }
      if( task.taskId === 3) { // 信用商业
        this.$router.push('/credit/businessService');
        return;
      }
      if(task.taskId === 4) { // 亲社会行为
        this.$router.push('/credit/prosocial');

      }

      // 其他任务保持原来的完成逻辑
      this.completeTask(task);
    },
    /** 完成任务 */
    completeTask(task) {
      this.$confirm('确认完成任务"' + task.taskName + '"？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 设置加载状态
        this.$set(task, 'loading', true);

        completeTask(task.taskId).then(response => {
          this.$modal.msgSuccess(response.msg);
          task.completed = true;
          this.getScoreInfo(); // 刷新信用分信息
          // this.getCreditHistory(); // 刷新历史记录
        }).catch(error => {
          this.$modal.msgError('任务完成失败：' + (error.message || '未知错误'));
        }).finally(() => {
          // 清除加载状态
          this.$set(task, 'loading', false);
        });
      });
    },
    /** 获取信用等级 */
    getCreditLevel(score) {
      if (score >= 800) return '优秀';
      if (score >= 700) return '良好';
      if (score >= 600) return '一般';
      if (score >= 500) return '较差';
      return '很差';
    },
    /** 获取任务类型图标 */
    getTaskIcon(taskType) {
      switch (taskType) {
        case '1': return '🏠'; // 生活服务
        case '2': return '🛒'; // 商业服务
        case '3': return '🤝'; // 亲社会行为
        default: return '📋';
      }
    },
    /** 获取任务类型标签类型 */
    getTaskTypeTagType(taskType) {
      switch (taskType) {
        case '1': return 'primary'; // 生活服务
        case '2': return 'success'; // 商业服务
        case '3': return 'warning'; // 亲社会行为
        default: return 'info';
      }
    },
    /** 获取任务类型名称 */
    getTaskTypeName(taskType) {
      switch (taskType) {
        case '1': return '生活服务';
        case '2': return '商业服务';
        case '3': return '亲社会行为';
        default: return '其他';
      }
    }
  }
};
</script>

<style scoped>
.score-card, .dimension-card, .task-card, .history-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.score-card:hover, .dimension-card:hover, .task-card:hover, .history-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  position: relative;
  padding-left: 12px;
}

.card-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 2px;
}

.score-display {
  text-align: center;
  padding: 30px 0;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  margin: 10px 0;
}

.score-number {
  font-size: 56px;
  font-weight: bold;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: 12px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.score-desc {
  font-size: 20px;
  color: #606266;
  margin-bottom: 12px;
  font-weight: 500;
}

.score-update-time {
  font-size: 13px;
  color: #909399;
  background: rgba(255, 255, 255, 0.8);
  padding: 4px 12px;
  border-radius: 12px;
  display: inline-block;
}

.task-item {
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
  background: #fff;
  position: relative;
  overflow: hidden;
}

.task-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transform: scaleY(0);
  transition: transform 0.3s ease;
}

.task-item:hover {
  border-color: #667eea;
  box-shadow: 0 4px 20px 0 rgba(102, 126, 234, 0.15);
  transform: translateY(-2px);
}

.task-item:hover::before {
  transform: scaleY(1);
}

.task-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.task-icon {
  margin-right: 8px;
  font-size: 18px;
}

.task-desc {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
  line-height: 1.6;
  padding-left: 24px;
}

.task-reward {
  font-size: 14px;
  color: #909399;
  margin-bottom: 15px;
  padding-left: 24px;
  display: flex;
  align-items: center;
}

.reward-label {
  margin-right: 4px;
}

.task-type-tag {
  margin-bottom: 15px;
  padding-left: 24px;
}

.reward-score {
  color: #E6A23C;
  font-weight: bold;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.task-action {
  text-align: right;
  padding-left: 24px;
}

.task-action .el-button {
  border-radius: 20px;
  padding: 8px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.task-action .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px 0 rgba(64, 158, 255, 0.3);
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 60px 0;
  font-size: 16px;
}

.no-data::before {
  content: '📊';
  display: block;
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

/* 守约记录样式 */
.compliance-content {
  padding: 10px;
}

.stats-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.stat-card {
  flex: 1;
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
  color: #1976d2;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.records-table {
  background-color: #f9f9f9;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #eee;
}

.table-header {
  display: flex;
  background-color: #f0f0f0;
  padding: 12px 16px;
  font-weight: 500;
  font-size: 14px;
}

.table-row {
  display: flex;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
  font-size: 14px;
  align-items: center;
}

.table-row:last-child {
  border-bottom: none;
}

.col-type {
  width: 100px;
  color: #666;
}

.col-desc {
  flex: 1;
}

.col-date {
  width: 100px;
  text-align: right;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .score-number {
    font-size: 42px;
  }

  .score-desc {
    font-size: 16px;
  }

  .task-item {
    padding: 15px;
  }

  .task-title {
    font-size: 16px;
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.score-card, .dimension-card, .task-card, .history-card {
  animation: fadeInUp 0.6s ease-out;
}

.task-item {
  animation: fadeInUp 0.6s ease-out;
  animation-delay: calc(var(--item-index, 0) * 0.1s);
}
</style>
